package com.obrock;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: Дмитрий Г. Кузнецов
 * Date: 15.10.12
 * Time: 16:33
 * To change this template use File | Settings | File Templates.
 */
public class ViewTemplates extends LinearLayout {
    int bgColor;
    Context context;

    Balance[] transfers = null;
    Balance selectedTransfer = null;

    public ViewTemplates(Context context) {
        super(context);
        this.context = context;
        this.bgColor = context.getResources().getColor(R.color.background_color);
        refresh();
    }

    public ViewTemplates(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.bgColor = context.getResources().getColor(R.color.background_color);
        refresh();
    }

    /*
    public ViewTransfers(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    */

    public Balance refresh() {
        inflate(context, R.layout.templates, this);
        //setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        setBackgroundColor(bgColor);

        TableLayout container = (TableLayout) findViewById(R.id.container_templates);
        container.setColumnShrinkable(1, true);
        container.setColumnStretchable(1, true);
        container.removeAllViews();

        /*
        TextView accountTitle = (TextView) findViewById(R.id.account_title);
        TextView accountBalance = (TextView) findViewById(R.id.account_amount);
        TextView accountDetails = (TextView) findViewById(R.id.account_debt);
        ImageView accountIcon = (ImageView) findViewById(R.id.icon);

        LinearLayout blockLines = (LinearLayout) findViewById(R.id.block_lines);
        LinearLayout blockColumns = (LinearLayout) findViewById(R.id.block_columns);
        */

        transfers = Main.db.getTemplates();

        if (selectedTransfer == null && transfers.length > 0) {
            selectedTransfer = transfers[0];
        }

        int id = -1;
        View current = null;
        TableRow xrow = null;

        for (int i = 0; i < transfers.length; ++i) {
            Balance transfer = transfers[i];
            //boolean approved = new Balance(selectedTransfer.parentID).approved(viewPeriod);

            double transferAmount = 0.0;
            String subTitle = "";

            ImageView icon = new ImageView(context);
            icon.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            icon.setAdjustViewBounds(true);
            icon.setMaxHeight(32);
            icon.setMaxWidth(32);
            icon.setPadding(0, 4, 0, 0);

            LinearLayout iconHolder = new LinearLayout(context);
            iconHolder.addView(icon);
            LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            iconHolder.setLayoutParams(param);

            transferAmount = transfer.amount;
            icon.setImageDrawable(getResources().getDrawable(R.drawable.bubble));
            subTitle = "";
            if (transfer.accountFrom != null) {
                subTitle += transfer.accountFrom.name;
            }
            if (transfer.accountTo != null) {
                if (subTitle.length() > 0) {
                    subTitle += " -> ";
                }
                subTitle += transfer.accountTo.name;
            }


            LinearLayout column2 = new LinearLayout(context);
            column2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column2.setOrientation(LinearLayout.VERTICAL);

            TextView name = Main.getTextView(context, transfer.name);
            name.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            name.setTextSize(16);

            LinearLayout subrow = new LinearLayout(context);
            subrow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            subrow.setOrientation(LinearLayout.HORIZONTAL);

            TextView date = Main.getTextView(context, Main.datetimeString(transfer.date));
            date.setTextSize(12);
            date.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            date.setTextColor(getResources().getColor(R.color.total_color));

            TextView sub = Main.getTextView(context, subTitle);
            sub.setTextSize(12);
            sub.setPadding(8, 0, 0, 0);

            subrow.addView(date);
            subrow.addView(sub);

            column2.addView(name);
            column2.addView(subrow);

            String anal = "";
            for (Analytics a : transfer.analytics.keySet()) {
                if (transfer.analytics.get(a) != null) {
                    if (anal.length() > 0) anal += ", ";
                    anal += transfer.analytics.get(a).name;
                }
            }

            if (anal.length() > 0) {
                TextView vanal = Main.getTextView(context, anal);
                vanal.setTextSize(12);
                vanal.setTextColor(getResources().getColor(R.color.list_color));
                column2.addView(vanal);
            }

            LinearLayout column3 = new LinearLayout(context);
            column3.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column3.setOrientation(LinearLayout.VERTICAL);

            xrow = Main.addRow(context, bgColor, i, new View[]{
                    iconHolder,
                    column2,
                    column3
            });

            xrow.setTag(Main.tagTemplate);

            xrow.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int id = view.getId();
                    selectedTransfer = transfers[id];
                    Main.setObject(Main.VIEW_TEMPLATES, selectedTransfer);
                    Main.refreshCursor((ViewGroup) view.getParent(), id, bgColor);
                    return false;
                }
            });

            xrow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {

                    ViewGroup v = (ViewGroup) view.getParent();
                    int id = view.getId();

                    selectedTransfer = transfers[view.getId()];
                    Main.doAction(Main.VIEW_TEMPLATES, selectedTransfer);
                }

            });

            Main.context.registerForContextMenu(xrow);
            container.addView(xrow);

            if (selectedTransfer != null && transfers[i].balanceID == selectedTransfer.balanceID) {
                id = i;
                if (current == null) {
                    current = xrow;
                }
            }

        }


        if (id != -1) {
            Main.refreshCursor(container, id, bgColor);
            ((ScrollView) findViewById(R.id.scroll_templates)).post(
                    new ScrollTo(((ScrollView) findViewById(R.id.scroll_templates)), current));
        }

        //Main.refreshHeader();
        return selectedTransfer;

        /*
        accountTitle.setText(getResources().getString(R.string.menu_templates));
        accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.bubble));
        accountBalance.setText("\n");
        accountDetails.setText("\n");
        */
    }

    void exportTemplates() {
        String fname = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + "obrock.templates";
        new File(fname).delete();
        try {
            FileWriter f = new FileWriter(fname);
            for(Balance x : transfers) {
                String from = (x.accountFrom == null || x.accountFrom.accountID == -1) ? "\r\n" : (x.accountFrom.name + "\r\n");
                String to = (x.accountTo == null || x.accountTo.accountID == -1) ? "\r\n" : (x.accountTo.name + "\r\n");
                String packet = "@\r\n"
                + x.name + "\r\n"
                + x.number + "\r\n"
                + x.key + "\r\n"
                + from
                + to
                + String.format("%d\r\n",x.flags)
                + "----\r\n"
                + x.template + "\r\n"
                + "----\r\n";
                f.write(packet);
            }
            f.flush();
            f.close();
            Main.toast(getResources().getString(R.string.file_write_success,fname));
        } catch (IOException e) {
            e.printStackTrace();
            Main.toast(getResources().getString(R.string.file_write_error,fname));
        }
    }

    void importTemplates() {
        String name = "";
        String number = "";
        String key = "";
        String from = "";
        String to = "";
        String template = "";
        int flags = 0;

        String fname = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + "obrock.templates";
        try {
            BufferedReader f = new BufferedReader(new FileReader(fname));
            String line = "";
            int cnt = 0;
            while((line = f.readLine()) != null) {
                if(!line.equals("@")) { break; }
                if((line = f.readLine()) == null) { break; }    name = line;
                if((line = f.readLine()) == null) { break; }    number = line;
                if((line = f.readLine()) == null) { break; }    key = line;
                if((line = f.readLine()) == null) { break; }    from = line;
                if((line = f.readLine()) == null) { break; }    to = line;
                if((line = f.readLine()) == null) { break; }    flags = Integer.parseInt(line);
                if((line = f.readLine()) == null) { break; }
                if(line.equals("----")) {
                    line = "";
                    while(true) {
                        line += (char)f.read();
                        if(line.contains("\r\n----\r\n")) {
                            break;
                        }
                    }
                    if(line.length() > 8) {
                        line = line.substring(0, line.length()-8);
                    }
                    template = line;
                }

                Balance balance = exists(name);
                if(balance == null) {
                    balance = new Balance(Main.db);
                    balance.mode = Balance.MODE_TEMPLATE;
                    balance.append();
                }

                balance.name = name;
                balance.number = number;
                balance.key = key;
                balance.accountFrom = Main.context.getAccountByName(from);
                balance.accountTo = Main.context.getAccountByName(to);
                balance.template = template;
                balance.flags = flags;
                balance.update();

            }
            f.close();
            Main.toast(getResources().getString(R.string.file_read_success,fname));
        } catch (IOException e) {
            e.printStackTrace();
            Main.toast(getResources().getString(R.string.file_read_error,fname));
        }
    }

    Balance exists(String name) {
        for(Balance x : transfers) {
            if(x.name.equals(name)) {
                return x;
            }
        }
        return null;
    }

}
